from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow
from PyQt5.QtCore import QCoreApplication, Qt, pyqtSlot, QPoint
from PyQt5.QtGui import QFont, QEnterEvent, QBitmap, QPainter, QPalette, QBrush, QPixmap
import sys

from ui.Mainwidget_ui import Ui_MainWidget
from ui.Mainwindow_ui import Ui_MainWindow


styleFile = './ui.qss'


class CommonHelper:
    def __init__(self):
        pass

    @staticmethod
    def readQss(style):
        with open(style, mode='r', encoding='utf-8') as f:
            return f.read()


# class MainWidget(QMainWindow, Ui_MainWindow):
class MainWidget(QWidget, Ui_MainWidget):
    """

    """
    def __init__(self, Licensed=False, parent=None):
        super(MainWidget, self).__init__(parent)
        self.setupUi(self)
        self._init_main_window()        # 主窗口初始化设置
        self._initDrag()                # 设置鼠标跟踪判断flag默认值
        self.setMouseTracking(True)     # 设置widget鼠标跟踪
        # self._close_max_min_icon()      # 设置 3 个按钮的图标字体
        self.Licensed = Licensed
        # self.Use_Qss()
        self.title_widget.installEventFilter(self)  # 初始化事件过滤器
        self.central_widget.installEventFilter(self)

    def _init_main_window(self):
        # 设置窗体无边框
        self.setWindowFlags(Qt.FramelessWindowHint)
        # 设置背景透明
        self.setAttribute(Qt.WA_TranslucentBackground)

    def _initDrag(self):
        # 设置鼠标跟踪判断flag默认值
        self._move_drag = False
        self._corner_drag = False
        self._bottom_drag = False
        self._right_drag = False

    def _close_max_min_icon(self):
        # 设置按钮图标使用webdings特殊字体
        self.min_bt.setFont(QFont("Webdings"))
        self.min_bt.setText('0')
        self.max_bt.setFont(QFont("Webdings"))
        self.max_bt.setText('1')
        self.close_bt.setFont(QFont("Webdings"))
        self.close_bt.setText('r')

    # def Use_Qss(self):
    #     with open("ui.qss", mode='r', encoding='utf-8') as fd:
    #         self.setStyleSheet(fd.read())

    @pyqtSlot()
    def on_min_bt_clicked(self):
        # 最小化
        self.showMinimized()

    @pyqtSlot()
    def on_max_bt_clicked(self):
        # 最大化与复原
        if self.isMaximized():
            self.showNormal()
            self.max_bt.setText('1')  # 切换放大按钮图标
            self.max_bt.setToolTip("<html><head/><body><p>最大化</p></body></html>")
        else:
            self.showMaximized()
            self.max_bt.setText('2')
            self.max_bt.setToolTip("<html><head/><body><p>恢复</p></body></html>")

    @pyqtSlot()
    def on_close_bt_clicked(self):
        # 关闭程序
        self.close()

    def eventFilter(self, obj, event):
        # 事件过滤器,用于解决鼠标进入其它控件后还原为标准鼠标样式
        if isinstance(event, QEnterEvent):
            self.setCursor(Qt.ArrowCursor)
        return super(MainWidget, self).eventFilter(obj, event)  #

    def resizeEvent(self, QResizeEvent):
        # 自定义窗口调整大小事件
        # 改变窗口大小的三个坐标范围
        self._right_rect = [QPoint(x, y) for x in range(self.width() - 5, self.width() + 5)
                            for y in range(self.title_widget.height() + 20, self.height() - 5)]

        self._bottom_rect = [QPoint(x, y) for x in range(1, self.width() - 5)
                             for y in range(self.height() - 5, self.height() + 1)]

        self._corner_rect = [QPoint(x, y) for x in range(self.width() - 5, self.width() + 1)
                             for y in range(self.height() - 5, self.height() + 1)]

    def mousePressEvent(self, event):
        # 重写鼠标点击的事件
        if (event.button() == Qt.LeftButton) and (event.pos() in self._corner_rect):
            # 鼠标左键点击右下角边界区域
            self._corner_drag = True
            event.accept()
        elif (event.button() == Qt.LeftButton) and (event.pos() in self._right_rect):
            # 鼠标左键点击右侧边界区域
            self._right_drag = True
            event.accept()
        elif (event.button() == Qt.LeftButton) and (event.pos() in self._bottom_rect):
            # 鼠标左键点击下侧边界区域
            self._bottom_drag = True
            event.accept()
        elif (event.button() == Qt.LeftButton) and (event.y() < self.title_widget.height()):
            # 鼠标左键点击标题栏区域
            self._move_drag = True
            self.move_DragPosition = event.globalPos() - self.pos()
            event.accept()

    def mouseMoveEvent(self, QMouseEvent):
        # 判断鼠标位置切换鼠标手势
        if QMouseEvent.pos() in self._corner_rect:  # QMouseEvent.pos()获取相对位置
            self.setCursor(Qt.SizeFDiagCursor)
        elif QMouseEvent.pos() in self._bottom_rect:
            self.setCursor(Qt.SizeVerCursor)
        elif QMouseEvent.pos() in self._right_rect:
            self.setCursor(Qt.SizeHorCursor)

        # 当鼠标左键点击不放及满足点击区域的要求后，分别实现不同的窗口调整
        # 没有定义左方和上方相关的5个方向，主要是因为实现起来不难，但是效果很差，拖放的时候窗口闪烁，再研究研究是否有更好的实现
        if Qt.LeftButton and self._right_drag:
            # 右侧调整窗口宽度
            self.resize(QMouseEvent.pos().x(), self.height())
            QMouseEvent.accept()
        elif Qt.LeftButton and self._bottom_drag:
            # 下侧调整窗口高度
            self.resize(self.width(), QMouseEvent.pos().y())
            QMouseEvent.accept()
        elif Qt.LeftButton and self._corner_drag:
            #  由于我窗口设置了圆角,这个调整大小相当于没有用了
            # 右下角同时调整高度和宽度
            self.resize(QMouseEvent.pos().x(), QMouseEvent.pos().y())
            QMouseEvent.accept()
        elif Qt.LeftButton and self._move_drag:
            # 标题栏拖放窗口位置
            self.move(QMouseEvent.globalPos() - self.move_DragPosition)
            QMouseEvent.accept()

    def mouseReleaseEvent(self, QMouseEvent):
        # 鼠标释放后，各扳机复位
        self._move_drag = False
        self._corner_drag = False
        self._bottom_drag = False
        self._right_drag = False


if __name__ == '__main__':
    # 适配2k等高分辨率屏幕,低分辨率屏幕可以缺省
    QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    ex = MainWidget()

    qssStyle = CommonHelper.readQss(styleFile)
    ex.setStyleSheet(qssStyle)

    ex.show()
    sys.exit(app.exec_())
